<script setup lang='ts'>
import { ref } from 'vue'
import type { UserItem } from '@/types/dept'
import type { comment } from '@/types/docter/comment'
import type { User, AppRegistrationDto } from '@/types/userDetails'
import type { Patient } from '@/types/sys/patient'
import { getUserDelailsList, getDeptByDeptId } from '@/services/userDetails'
import {deleteRegistrationById, getAppRegistrationDto,getAppointmentsBypatientId} from '../../services/docter/patient'
import { onLoad } from '@dcloudio/uni-app'
import {
  getDictData,
  findDict,
  getDatesubstring,
  getDate,
  getAverage,
  geiTime,
} from '../../utils/util'
import type { DictData } from '@/types/global'
import { getMyScheduling } from '@/services/userDetails'
import { getComment } from '@/services/docter/comment'
import type { myScheduling, myData } from '@/types/myScheduling'
import { useMemberStore } from '@/stores'

const memberStore = useMemberStore()
const profile = memberStore.profile
// uniapp 获取页面参数
const query = defineProps<{
  userId: string;
}>()

	//User表的全部数据
	const userList = ref < User > ()

	//获取表User的全部数据
	const getUserListData = async () => {
		const res = await getUserDelailsList(query.userId)
		userList.value = res.data
		getDeptByDeptIdData()
	}

	//部门表的全部数据
	const deptList = ref < UserItem > ()
	//获取部门的数据
	const getDeptByDeptIdData = async () => {
		const res = await getDeptByDeptId(String(userList.value?.deptId))
		deptList.value = res.data
	}

//挂号处理
const getAppRegistrationData = async (ev: AppRegistrationDto) => {
  const res = await getAppRegistrationDto(ev)
}

//患者评论数据
const commitDate = ref<comment>()
//获取患者评论数据
const getCommentDate = async () => {
  const res = await getComment(query.userId)
  commitDate.value = res.data
}

	// 获取sys_user_background字典的数据
	const backgroundList = ref < DictData[] > ([])
	const getBackgroundList = async () => {
		const res = await findDict('sys_user_background')
		backgroundList.value = res.data
	}

	// 获取sys_user_background字典的数据
	const userRankList = ref < DictData[] > ([])
	const getuserRankList = async () => {
		const res = await findDict('sys_user_level')
		userRankList.value = res.data
	}

	//我的排班数据
	const mySchedulingData = ref < myScheduling > ()
	const myScheData = ref < myData > ()

//获取我的排班数据
const getMySchedulingData = async () => {
  const res = await getMyScheduling({
    userId: query.userId,
  });

  // 将后端返回的数据转换为前端需要的格式
  const transformedData: myScheduling = {
    beginDate: res.data.startTimeThisWeek,
    endDate: res.data.endTimeThisWeek,
    labelNames: res.data.labelNames,
    tableData: res.data.schedulingDtos.map((item: any) => ({
      userId: item.userId,
      deptId: item.deptId,
      subsectionType: item.subsectionType,
      schedulingType: item.schedulingType,
    })),
  };

  // 应用 geiTime 函数处理转换后的数据
  mySchedulingData.value = geiTime(transformedData);
};

const scroll: UniHelper.ScrollViewOnScroll = (e) => {
}
const formatVisitDate = (visitDate) => {
  const date = new Date(visitDate);
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 获取月份，补足两位
  const day = String(date.getDate()).padStart(2, '0'); // 获取日期，补足两位
  const weekDayMap = ['日', '一', '二', '三', '四', '五', '六']; // 映射星期
  const weekDay = `周${weekDayMap[date.getDay()]}`; // 获取星期几

  return `${month}-${day}${weekDay}`; // 返回格式化后的日期
};

// 检查用户预约状态的函数
const checkAppointments = async () => {
  try {
    const registrationStatusVo = {
      userId: query?.userId || '',
      patientId: profile?.patientId || '',
    };
    const appointments = await getAppointmentsBypatientId(registrationStatusVo);

    appointments.forEach((appointment) => {
      const formattedDate = formatVisitDate(appointment.visitDate);
      const key = `${formattedDate}-${appointment.subsectionType}`;
      appointmentStatus.value[key] = true; // 标记为已预约

      registrationIds.value[key] = appointment.registrationId; // 存储注册ID
    });
  } catch (error) {
    console.error("获取预约状态失败:", error);
  }
};


// 新增：预约状态管理
const appointmentStatus = ref<{ [key: string]: boolean }>({})

// 新增：存储每个预约的 registrationId
const registrationIds = ref<{ [key: string]: string }>({});

// 修改：预约处理函数
const firm = (ev: string, day: string, va: string) => {
  if (!profile) {
    uni.showToast({ icon: 'none', title: '请先登录' });
    return; // 提示用户后直接返回，阻止后续操作
  }

  if (va != '1') {
    return null;
  }

  const appointmentKey = `${day}-${ev}`;

  if (appointmentStatus.value[appointmentKey]) {
    // 如果已预约，询问是否取消
    uni.showModal({
      title: '提示',
      content: '您确定要取消预约吗？',
      success: async function(res) {  // 使用 async 函数以便处理异步删除
        if (res.confirm) {
          try {

            await deleteRegistrationById(registrationIds.value[appointmentKey]); // 调用删除函数
            appointmentStatus.value[appointmentKey] = false;
            registrationIds.value[appointmentKey] = ''; // 清空取消后的 ID
            uni.showToast({ icon: 'success', title: '取消预约成功' });
          } catch (error) {

            uni.showToast({ icon: 'none', title: '取消预约失败' });
          }
        }
      }
    });
  } else {
    // 如果未预约，询问是否预约
    uni.showModal({
      title: '提示',
      content: '是否挂' + day + '(' + (ev === '1' ? '上午' : ev == '2' ? '下午' : '晚上') + ')的号',
      success: async function(res) {  // 使用 async 函数
        if (res.confirm) {
          const registrationDto: AppRegistrationDto = {
            patientId: profile?.patientId,
            patientName: profile?.name,
            userId: userList.value?.userId,
            doctorName: userList.value?.userName,
            deptId: deptList.value?.deptId,
            subsectionType: ev,
            visitDate: day,
          };

          try {
            const registration = await getAppRegistrationDto(registrationDto);

            if (registration && registration.registrationId) {
              registrationIds.value[appointmentKey] = registration.registrationId; // 存储注册的id用于取消
              appointmentStatus.value[appointmentKey] = true;
              uni.showToast({ icon: 'success', title: '预约成功' });
            }

            // 这里可以使用 registration 对象进行进一步处理

          } catch (error) {
            uni.showToast({ icon: 'none', title: '挂号失败' });
          }
        } else if (res.cancel) {
          uni.showToast({ icon: 'none', title: '取消挂号' });
        }
      },
    });
  }
};

	const imageStyles = ref({})

const backgroundData = ''
onLoad(() => {
  Promise.all([
    getBackgroundList(),
    getuserRankList(),
    getUserListData(),
    getCommentDate(),
    getMySchedulingData(),
    checkAppointments(), // 添加这个函数来检查预约状态
  ])
})
</script>
<template>
  <view class='userDetail'>
    <view class='picture'>
      <image :src='userList?.picture' mode='scaleToFill' />
      <text class='rate'>
        <uni-rate
            :readonly='true'
            :value='getAverage(commitDate)'
            size='40rpx'
        />
      </text>
    </view>

		<view class='name'>
			<text class='name2'>
				<text class='bold'>{{ userList?.userName }} &nbsp;</text>
				{{ deptList?.deptName }} &nbsp;{{
          getDictData(userRankList, userList?.userRank!)
        }}
			</text>
			<text class='deptName'></text>
		</view>
		<view class='main'>
			<view>
				<text class='Green1'>简介:&nbsp;</text>
				{{ userList?.userName }},&nbsp;
				{{ userList?.sex == '1' ? '男' : '女' }},&nbsp;{{
          getDictData(userRankList, userList?.userRank!)
        }},&nbsp;{{ userList?.introduction }}
			</view>
			<br />
			<view>
				<text class='Green2'>擅长:&nbsp;</text>
				<uni-tag :circle='true' :text='userList?.strong' type='success' size='small' />
			</view>
		</view>

    <view class='gh'>
      <text
          class='title'
          style='
          background-image: linear-gradient(to bottom right, #3ece80, #ffffff);
        '
      >医院门诊挂号
      </text>
      <scroll-view
          class='scroll-view_H'
          scroll-x='true'
          scroll-with-animation='true'
          @scroll='scroll'
          scroll-left='120'
      >
        <view class='mySch'>
          <table class='tab'>
            <tr>
              <td style='width: 80px; height: 30px'></td>
              <td
                  v-for='(value, key, index) in mySchedulingData?.labelNames'
                  :key='index'
              >
                <span class='date'>{{ getDatesubstring(value).date }}</span>
              </td>
            </tr>
            <tr>
              <td style='width: 40px; height: 30px'></td>
              <td
                  style='width: 40px; height: 20px'
                  v-for='(value, key, index) in mySchedulingData?.labelNames'
                  :key='index'
              >
                <span class='day'>{{ getDatesubstring(value).day }}</span>
              </td>
            </tr>
            <tr
                class='main'
                v-for='(value, key, index) in mySchedulingData?.tableData'
                :key='index'
            >
              <td>
                <text class='time'>{{
                    value.subsectionType == '1'
                        ? '上午'
                        : value.subsectionType == '2'
                            ? '下午'
                            : '晚上'
                  }}
                </text>
              </td>
              <td
                  class='yuyue'
                  v-for='(va,index2) in value.schedulingType'
                  :key='index2'
              >
                <button
                    class='but'
                    :style="{
                    backgroundColor: va === '1' ? '#3ece80' : '#dddddd',
                  }"
                    @tap='
                    firm(
                      value.subsectionType,
                      mySchedulingData!.labelNames[index2],
                      va
                    )
                  '
                >
                  <span class='font1' style='color: #ffffff'>{{
                      va == '1'
                          ? (appointmentStatus[`${mySchedulingData!.labelNames[index2]}-${value.subsectionType}`]
                              ? '已预'
                              : '预约')
                          : '无号'
                    }}</span>
                </button>
              </td>
            </tr>
          </table>
        </view>
      </scroll-view>
    </view>

		<view class='comment'>
			<text class='title' style='
          background-image: linear-gradient(to bottom right, #3ece80, #ffffff);
        '>患者评价
			</text>
			<uni-list>
				<uni-list :border='true'>
					<!-- 显示圆形头像 -commitDate staff-filled-->
					<div v-for='(value, key, index) in commitDate' :key='index'>
						<!-- <uni-list-chat
              :avatar-circle='true'
              :title='value.name'
              :avatar='url2'
              :note='value.content'
              :time='value.addTime'
            >
              <span style='font-size: 70%; color: #525453'>{{
                  getDate(value.addTime)
                }}</span>
              <text>
                <uni-rate :readonly='true' :value='value.star' size='30rpx' />
              </text>
			  <strong></strong>
            </uni-list-chat> -->
						<view class="uni-comment-list">
							<view class="uni-comment-face">
								<image :src='value.picUrls' mode="widthFix"></image>
							</view>
							<view class="uni-comment-body">
								<span style='font-size: 70%; color: #525453'>{{getDate(value.addTime)}}</span>
								<text>
									<uni-rate :readonly='true' :value='value.star' size='30rpx' />
								</text>
								<view class="uni-comment-content">{{value.content}}</view>
							</view>
						</view>

					</div>
				</uni-list>
			</uni-list>
		</view>
	</view>
</template>

<style scoped lang='scss'>
	.scroll-view_H {
		white-space: nowrap;
		width: 100%;
	}

	.title {
		margin-left: 20rpx;
		margin-bottom: 20rpx;
	}

	.gh {
		margin-top: 50rpx;
	}

	.comment {
		margin-top: 50rpx;
	}

	.userDetail {
		width: 100%;
		// padding: 30rpx

		.picture {
			// width: 180rpx;
			// height: 180rpx;
			padding: 20rpx;
			height: 300rpx;
			background-size: 100% auto;
			background-image: url(https://hos-health.oss-cn-guangzhou.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20231221164149.jpg);
			vertical-align: middle;

			image {
				width: 180rpx;
				border-radius: 50%;
				height: 180rpx;
				vertical-align: middle;
				margin: 45rpx 12rpx;
			}
		}

		.name {
			.name2 {
				position: relative;
				left: 55rpx;

				.bold {
					font-size: 42rpx;
					font-weight: 900;
				}
			}
		}

		.main {
			margin-top: 30rpx;
			padding: 0 40rpx;

			.Green1 {
				color: #8bd085;
			}

			.Green2 {
				color: #8bd085;
			}
		}

		.rate {
			position: relative;
			top: -60rpx;
			left: 3rpx;
		}

		.mySch {
			position: relative;
			white-space: nowrap;
			padding: 0 40rpx;

    .tab {
      table-layout: fixed;
      width: 2000rpx;
      height: 50rpx;

				.break {
					width: 100rpx;
					height: 100rpx;
					white-space: nowrap;
				}

				.date {
					font-size: 80%;
					position: relative;
					left: 25rpx;
					top: 10rpx;
				}

				.day {
					position: relative;
					left: 30rpx;
					font-weight: 40;
					color: #a59eb0;
					font-size: 80%;
				}

				.main {
					.time {
						color: #a59eb0;
						font-size: 80%;
					}

        .yuyue {
          .but {
            width: 40px;
            height: 40px;
            border-radius: 60%;
            font-size: 20px;
          }

						.font1 {
							font-size: 80%;
							position: relative;
							top: -20rpx;
							left: -20rpx;
						}
					}
				}
			}
		}
	}

.circle-button {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #dddddd;
  font-size: 24px;
}

	.circle-button text {
		color: #ffffff;
		font-size: 40%;
		position: relative;
		top: -20rpx;
		left: 0rpx;
	}

	/* 评论 */
	.uni-comment {
		padding: 5rpx 0;
		display: flex;
		flex-grow: 1;
		flex-direction: column;
	}

	.uni-comment-list {
		flex-wrap: nowrap;
		padding: 10rpx 0;
		margin: 10rpx 0;
		width: 100%;
		display: flex;
	}

	.uni-comment-face {
		width: 70upx;
		height: 70upx;
		border-radius: 100%;
		margin-right: 20upx;
		flex-shrink: 0;
		overflow: hidden;
	}

	.uni-comment-face image {
		width: 100%;
		border-radius: 100%;
	}

	.uni-comment-body {
		width: 100%;
	}

	.uni-comment-top {
		line-height: 1.5em;
		justify-content: space-between;
	}

	.uni-comment-top text {
		color: #0A98D5;
		font-size: 24upx;
	}

	.uni-comment-date {
		line-height: 38upx;
		flex-direction: row;
		justify-content: space-between;
		display: flex !important;
		flex-grow: 1;
	}

	.uni-comment-date view {
		color: #666666;
		font-size: 24upx;
		line-height: 38upx;
	}

	.uni-comment-content {
		line-height: 1.6em;
		font-size: 28upx;
		padding: 8rpx 0;
	}

	.uni-comment-replay-btn {
		background: #FFF;
		font-size: 24upx;
		line-height: 28upx;
		padding: 5rpx 20upx;
		border-radius: 30upx;
		color: #333 !important;
		margin: 0 10upx;
	}
</style>
